console.log("background js");

sogouExplorer.browserAction.onClicked.addListener(function(tab) {
    sogouExplorer.tabs.executeScript(null, {file: "jquery-3.6.0.min.js"});
    sogouExplorer.tabs.executeScript(null, {file: "content_script.js"});
});

sogouExplorer.runtime.onMessage.addListener(function (request,sender,callback) {
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");

    if (request.imgObj){

        console.log(request.imgObj);

        var blob = dataURLtoFile(request.imgObj, 'image/jpeg');
        var files = new window.File([blob], new Date().getTime() + '.jpg', {type: 'image/jpeg'});

        var formData = new FormData();
        formData.append("file", files);

        $.ajax({
            url:'http://127.0.0.1:8100/upload',
            type:'post',
            async:false,
            data: formData,
            contentType: false,
            processData: false,
            success:function(res){
                console.log(res);
                callback({resp: res});
            }
        });
        
    }
    else{
        callback({});
    }
       
});

function dataURLtoFile(dataURI, type) {
    let binary = atob(dataURI.split(',')[1]);
    let array = [];
    for(let i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type:type });
}